In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly
import plotly.graph_objects as go
import re
import math
import pickle
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import time
# magic word for producing visualizations in notebook
%matplotlib inline
'''
Import note: The classroom currently uses sklearn version 0.19.
If you need to use an imputer, it is available in sklearn.preprocessing.Imputer,
instead of sklearn.impute as in newer versions of sklearn.
'''
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', sep=";")
# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', sep = ";")
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
display(azdias.head(5))
display(feat_info.head())
azdias.describe()
nulls_count = azdias.isnull().sum()
nulls_count_df = pd.DataFrame(nulls_count).reset_index().rename(columns={'index':'feature',0:'count'})
nulls_count_df['percentage'] = nulls_count_df['count']/azdias.shape[0]
nulls_count_df.head(4)
# Plot missing values
fig = go.Figure(data =
(
go.Bar(x=nulls_count_df['feature'],
y=nulls_count_df['percentage'].sort_values(ascending = False),
marker_color = '#ABDDDE',
marker_line_width = 1,
marker_line_color = 'black'
)
),
layout = go.Layout(bargap = 0.25,
title = {'text':'Sampling distribution - means', 'x': 0.5},
xaxis_title="Features",
yaxis_title="Proportions"
),
)
fig.show()
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
# Identify missing or unknown data values and convert them to NaNs.
## Copy data
feat_info_clean_df = feat_info.copy(deep=True)
azdias_clean_df = azdias.copy(deep=True)
feat_info_clean_df.missing_or_unknown[1]
## Define list split function
def list_split(x):
return re.sub('[ \[ \] ]', '', x).split(",")
## Apply function to 'missing_or_unkown' column
feat_info_clean_df.missing_or_unknown = feat_info_clean_df.missing_or_unknown.apply(list_split)
feat_info_clean_df.set_index(['attribute'], inplace=True)
feat_info_clean_df.missing_or_unknown[1]
for attr in feat_info_clean_df.index: ## For each column attribute
for x in feat_info_clean_df.loc[attr]['missing_or_unknown']: ## Extract number values in that column
try:
azdias_clean_df[attr].replace(int(x), np.nan, inplace=True) ## Replace those number values by NaN
except ValueError:
azdias_clean_df[attr].replace(x, np.nan, inplace=True) ## Exception if value error (not int), then replace whole x with nan
azdias_clean_df.sample(n=2)
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
# Investigate patterns in the amount of missing data in each column.
cleaned_nulls_count = azdias_clean_df.isnull().sum()
cleaned_nulls_count_df = pd.DataFrame(cleaned_nulls_count).reset_index().rename(columns={'index':'feature',0:'count'})
cleaned_nulls_count_df['percentage'] = cleaned_nulls_count_df['count']/azdias_clean_df.shape[0]
cleaned_nulls_count_df.sort_values(by = 'percentage', ascending = False, inplace=True)
fig = go.Figure(data =
(
go.Bar(x=cleaned_nulls_count_df['feature'],
y=cleaned_nulls_count_df['percentage'],
marker_color = '#ABDDDE',
#text = cleaned_nulls_count_df['percentage'],
#texttemplate='%{text:.2s}',
#textposition='outside',
marker_line_width = 1,
marker_line_color = 'black'
)
),
layout = go.Layout(bargap = 0.25,
title = {'text':'Missing values distribution after cleansing', 'x': 0.5},
xaxis_title = "Features",
yaxis_title = "Proportions"
),
)
fig.show()
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
outlier_columns = cleaned_nulls_count_df[cleaned_nulls_count_df.percentage > 0.3]['feature']
azdias_clean_df.drop(outlier_columns, axis=1, inplace=True)
display('Dropped columns are:', outlier_columns)
azdias_clean_df.shape
We can see that the first column TITLE_KZ has 99%+ missing values .. I've sorted them in descending order, now we know we can stop at the ALTER_HH column where it is missing 34% of the data. You can see above the column names I've dropped.
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
# How much data is missing in each row of the dataset?
cleaned_nullrows_count = azdias_clean_df.isnull().sum(axis=1)
cleaned_nullrows_count_df = pd.DataFrame(cleaned_nullrows_count).reset_index().rename(columns={'index':'row',0:'count'})
cleaned_nullrows_count_df['percentage'] = cleaned_nullrows_count_df['count']/azdias_clean_df.shape[1]
cleaned_nullrows_count_df.sort_values(['row'], inplace=True)
fig = go.Figure(data =
(
go.Histogram(x=cleaned_nullrows_count_df.query("count != 0")['count'],
marker_color = '#ABDDDE',
#text = cleaned_nulls_count_df['percentage'],
#texttemplate='%{text:.2s}',
#textposition='outside',
marker_line_width = 1,
marker_line_color = 'black'
)
),
layout = go.Layout(bargap = 0.25,
title = {'text':'Missing (row) values distribution after cleansing', 'x': 0.5},
xaxis_tickmode = 'linear',
xaxis_title = "column(s) count per row",
yaxis_title = "frequency",
),
)
fig.show()
# Write code to divide the data into two subsets based on the number of missing
# values in each row.
lesseq_than_10 = cleaned_nullrows_count_df[cleaned_nullrows_count_df['count'] <= 10]
more_than_10 = cleaned_nullrows_count_df[cleaned_nullrows_count_df['count'] > 10]
# Validation #
print('Validation: ',cleaned_nullrows_count_df.shape[0] == lesseq_than_10.shape[0] + more_than_10.shape[0])
print(lesseq_than_10.shape[0] / cleaned_nullrows_count_df.shape[0])
print(more_than_10.shape[0] / cleaned_nullrows_count_df.shape[0])
import warnings
warnings.filterwarnings('ignore')
le_10_grp = azdias_clean_df.loc[lesseq_than_10.index].isnull().sum()/azdias_clean_df.loc[lesseq_than_10.index].shape[0]
mt_10_grp = azdias_clean_df.loc[more_than_10.index].isnull().sum()/azdias_clean_df.loc[more_than_10.index].shape[0]
fig = go.Figure(layout = go.Layout(title = {'text':'Missing (row) groups prop. after cleansing', 'x': 0.5},
xaxis_title = "Features",
yaxis_title = "Proportions"))
fig.add_trace(go.Bar(x=le_10_grp.index,
y=le_10_grp.values,
name='Less than/equal 10',
marker_color='rgb(244, 181, 189)'
))
fig.add_trace(go.Bar(x=mt_10_grp.index,
y=mt_10_grp.values,
name='More than 10',
marker_color='#ABDDDE'
))
We can observe here that 88% of the rows have less than or equal than 10 missing columns, on the other hand rows that have More than 10 missing columns account for 12%. Each legend in the plot as seen is a group.
Now, let's apply each group on each column, separetly to see if the frequency of certain rows missing that column.
We can see that the frequency for the red less than or equal than 10 group is nearly less than 1% for all the columns, while the frequency for More than 10 are mostly above 60% for more than half of the columns.
We're not going to drop rows for now, we will drop rows later in the project.
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
# How many features are there of each data type?
print(feat_info.type.value_counts())
cat_columns = feat_info.query("type == 'categorical'")['attribute']
mixed_columns = feat_info.query("type == 'mixed'")['attribute']
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
uniq_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].nunique(), columns=['nunique'])
type_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].dtypes, columns=['dtype'])
cat_columns_df = pd.concat([uniq_df,type_df], axis=1).sort_values(by='nunique')
cat_columns_df
## Changing that binary non-numeric column to 0 and 1 ##
azdias_clean_df.replace({'OST_WEST_KZ':{'W': 0, 'O': 1}}, inplace=True)
## Validation ##
azdias_clean_df['OST_WEST_KZ'].unique()
## Dropping multivariate columns ##
azdias_clean_df.drop(cat_columns_df[cat_columns_df['nunique']>=3].index, axis=1, inplace=True)
azdias_clean_df.shape
I have created a helper df that shows the number of unique values and the data type for the categorical features.
OST_WEST_KZ that takes non-numerical ['W','O'] to 0 and 1 respectively.There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md for the details needed to finish these tasks.
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
def get_decade(x):
if x in (1,2):
return 1
elif x in (3,4):
return 2
elif x in (5,6,7):
return 3
elif x in (8,9):
return 4
elif x in (10,11,12,13):
return 5
elif x != str:
return x
else:
return 6
def get_region(x):
if x in (1,2,3,4,5,8,9,14,15):
return 1
elif x in (6,10,11):
return 2
elif x in (7,12,13):
return 3
elif x != str:
return x
else:
return 4
azdias_clean_df['PRAEGENDE_JUGENDJAHRE_DECADE'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_decade)
azdias_clean_df['PRAEGENDE_JUGENDJAHRE_REGION'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_region)
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
def str_range(x,y):
return [str(i).zfill(2) for i in range(x,y+1)]
def get_wealth(x):
if x in str_range(11,15):
return 1
elif x in str_range(21,25):
return 2
elif x in str_range(31,35):
return 3
elif x in str_range(41,45):
return 4
elif x in str_range(51,55):
return 5
elif x != str:
return x
else:
return 6
def life_stage(x):
if x in ('11','21','31','41','51'):
return 1
if x in ('12','22','32','42','52'):
return 2
if x in ('13','23','33','43','53'):
return 3
if x in ('14','24','34','44','54'):
return 3
if x in ('15','25','35','45','55'):
return 4
elif x != str:
return x
else:
return 5
azdias_clean_df['CAMEO_INTL_2015_WEALTH'] = azdias_clean_df['CAMEO_INTL_2015'].apply(get_wealth)
azdias_clean_df['CAMEO_INTL_2015_LIFE_STAGE'] = azdias_clean_df['CAMEO_INTL_2015'].apply(life_stage)
I have created the following features:
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)
azdias_clean_df.drop(['PRAEGENDE_JUGENDJAHRE','CAMEO_INTL_2015'], axis=1, inplace=True)
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
azdias_clean_df.head(2)
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
def clean_data(df):
"""
Perform feature trimming, re-encoding, and engineering for demographics
data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
# Put in code here to execute all main cleaning steps:
## convert missing value codes into NaNs, ...
# Copy Data
feat_info_clean_df = feat_info.copy(deep=True)
azdias_clean_df = df.copy(deep=True)
# Remove symbols
feat_info_clean_df.missing_or_unknown = feat_info_clean_df.missing_or_unknown.apply(list_split)
feat_info_clean_df.set_index(['attribute'], inplace=True)
# Replace
for attr in feat_info_clean_df.index: ## For each column attribute
for x in feat_info_clean_df.loc[attr]['missing_or_unknown']: ## Extract number values in that column
try:
azdias_clean_df[attr].replace(int(x), np.nan, inplace=True) ## Replace those number values by NaN
except ValueError:
azdias_clean_df[attr].replace(x, np.nan, inplace=True) ## Exception if value error (not int), then replace whole x with nan
## remove selected columns and rows, ...
# Remove columns hosting 30%+ Nulls
cleaned_nulls_count = azdias_clean_df.isnull().sum()
cleaned_nulls_count_df = pd.DataFrame(cleaned_nulls_count).reset_index().rename(columns={'index':'feature',0:'count'})
cleaned_nulls_count_df['percentage'] = cleaned_nulls_count_df['count']/azdias_clean_df.shape[0]
cleaned_nulls_count_df.sort_values(by = 'percentage', ascending = False, inplace=True)
outlier_columns = cleaned_nulls_count_df[cleaned_nulls_count_df.percentage > 0.3]['feature']
azdias_clean_df.drop(outlier_columns, axis=1, inplace=True)
# Remove rows more than 10 missing values
cleaned_nullrows_count = azdias_clean_df.isnull().sum(axis=1)
cleaned_nullrows_count_df = pd.DataFrame(cleaned_nullrows_count).reset_index().rename(columns={'index':'row',0:'count'})
cleaned_nullrows_count_df['percentage'] = cleaned_nullrows_count_df['count']/azdias_clean_df.shape[1]
outlier_rows = cleaned_nullrows_count_df[cleaned_nullrows_count_df['count'] > 10].index
azdias_clean_df.drop(outlier_rows, axis=0, inplace=True)
## select, re-encode, and engineer column values.
# Re-Encode categorical non-numerical column
azdias_clean_df.replace({'OST_WEST_KZ':{'W': 0, 'O': 1}}, inplace=True)
# Drop multivariate columns (variates > 3)
cat_columns = feat_info.query("type == 'categorical'")['attribute']
mixed_columns = feat_info.query("type == 'mixed'")['attribute']
uniq_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].nunique(), columns=['nunique'])
type_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].dtypes, columns=['dtype'])
cat_columns_df = pd.concat([uniq_df,type_df], axis=1).sort_values(by='nunique')
azdias_clean_df.drop(cat_columns_df[cat_columns_df['nunique']>=3].index, axis=1, inplace=True)
# Mixed columns
azdias_clean_df['PRAEGENDE_JUGENDJAHRE_DECADE'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_decade)
azdias_clean_df['PRAEGENDE_JUGENDJAHRE_REGION'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_region)
azdias_clean_df['CAMEO_INTL_2015_WEALTH'] = azdias_clean_df['CAMEO_INTL_2015'].apply(get_wealth)
azdias_clean_df['CAMEO_INTL_2015_LIFE_STAGE'] = azdias_clean_df['CAMEO_INTL_2015'].apply(life_stage)
azdias_clean_df.drop(['PRAEGENDE_JUGENDJAHRE','CAMEO_INTL_2015'], axis=1, inplace=True)
print("Original shape:", df.shape)
print("After cleansing shape:", azdias_clean_df.shape)
return azdias_clean_df
## Return the cleaned dataframe.
azdias_clean_df = clean_data(azdias)
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
azdias_clean_df.isnull().sum().sort_values(ascending=False) / len(azdias_clean_df) * 100
azdias_clean_df = azdias_clean_df.sub(azdias_clean_df.mean())/azdias_clean_df.std()
## Instantiate an imputer ##
mean_imputer = SimpleImputer(missing_values=np.nan, strategy='mean', copy=False)
## Fit an imputer ##
mean_imputer.fit(azdias_clean_df)
## Transform using imputer ##
mean_imputer.transform(azdias_clean_df)
## Validate all nulls are dropped ##
print("[validation] Unique nulls sum: ",np.unique(azdias_clean_df.isnull().sum(axis=1)))
print("Shape after cleaning: ", azdias_clean_df.shape)
sklearn standard scalar takes into account missing nan values, meaning if we have a column of 4 values and one nan, it will divide on 5.
So I'm going to play with df.sub, df.mean and df.std to calculate the mean of columns and standard deivation excluding the nans which divides on row number excluding nans. I've simulated this way and the numbers matches the standard scaler of sklearn's. The validation can be done when having a mean of 0 and a std of 1 for each column, this has to be done using np.nanmean()
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.# Apply PCA to the data.
def do_pca(n_components, data):
'''
Transforms data using PCA to create n_components, and provides back the results of the
transformation.
INPUT: n_components - int - the number of principal components to create
data - the data you would like to transform
OUTPUT: pca - the pca object created after fitting the data
X_pca - the transformed X matrix with new number of components
'''
pca = PCA(n_components)
X_pca = pca.fit_transform(data)
return pca, X_pca
pca, X_pca = do_pca(68,azdias_clean_df)
# Investigate the variance accounted for by each principal component.
def scree_plot(pca):
'''
Creates a scree plot associated with the principal components
INPUT: pca - the result of instantian of PCA in scikit learn
OUTPUT:
None
'''
num_components=len(pca.explained_variance_ratio_)
ind = np.arange(num_components)
vals = pca.explained_variance_ratio_
plt.figure(figsize=(15, 10))
ax = plt.subplot(111)
cumvals = np.cumsum(vals)
ax.bar(ind, vals)
ax.plot(ind, cumvals)
for i in range(num_components):
ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]),
va="bottom",
ha="center",
fontsize=10,
rotation = 90)
ax.xaxis.set_tick_params(width=0)
ax.yaxis.set_tick_params(width=2, length=11)
ax.set_xlabel("Principal Component")
ax.set_ylabel("Variance Explained (%)")
plt.title('Explained Variance Per Principal Component')
scree_plot(pca)
# Re-apply PCA to the data while selecting for number of components to retain.
pca, X_pca = do_pca(25,azdias_clean_df)
scree_plot(pca)
We can see that we're reaching 80.5% variance by the 23rd component.
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
def pca_results(full_dataset, pca, n_comp, visual=True):
'''
Create a DataFrame of the PCA results
Includes dimension feature weights and explained variance
Visualizes the PCA results
'''
# Dimension indexing
dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,n_comp+1)]
# PCA components
components = pd.DataFrame(np.round(pca.components_[1:n_comp+1], 4), columns = full_dataset.keys())
components.index = dimensions
# PCA explained variance
ratios = pca.explained_variance_ratio_[0:n_comp].reshape(n_comp, 1)
variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
variance_ratios.index = dimensions
if visual == True:
# Create a bar plot visualization
fig, ax = plt.subplots(figsize = (14,8))
# Plot the feature weights as a function of the components
components.plot(ax = ax, kind = 'bar');
ax.set_ylabel("Feature Weights")
ax.set_xticklabels(dimensions, rotation=0)
ax.get_legend().remove()
# Display the explained variance ratios
for i, ev in enumerate(pca.explained_variance_ratio_[0:n_comp]):
ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n %.4f"%(ev))
else:
# Return a concatenated DataFrame
return pd.concat([variance_ratios, components], axis = 1)
pca_results(azdias_clean_df,pca,3, visual=False)
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
pca_01_df = pd.DataFrame(np.round(pca.components_[0:1], 4), columns = azdias_clean_df.keys()).T.rename(columns={0:'Weight'})
pca_01_df['Weight_abs'] = np.abs(pca_01_df['Weight'])
pca_01_df.sort_values(by = 'Weight_abs', ascending=False)[:10]
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pca_02_df = pd.DataFrame(np.round(pca.components_[1:2], 4), columns = azdias_clean_df.keys()).T.rename(columns={0:'Weight'})
pca_02_df['Weight_abs'] = np.abs(pca_02_df['Weight'])
pca_02_df.sort_values(by = 'Weight_abs', ascending=False)[:10]
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pca_03_df = pd.DataFrame(np.round(pca.components_[2:3], 4), columns = azdias_clean_df.keys()).T.rename(columns={0:'Weight'})
pca_03_df['Weight_abs'] = np.abs(pca_03_df['Weight'])
pca_03_df.sort_values(by = 'Weight_abs', ascending=False)[:10]
pca_results(azdias_clean_df,pca,3, visual=True)
PCA-1
- MOBI_REGIO: Movement patterns
- PLZ8_ANTG3: Number of 6-10 family houses in the PLZ8 region
- PLZ8_ANTG1: Number of 1-2 family houses in the PLZ8 region
- PLZ8_ANTG4: Number of 10+ family houses in the PLZ8 region
- PLZ8_BAUMAX: Most common building type within the PLZ8 region
- CAMEO_INTL_2015_WEALTH: Wealth of family
In the positive co-relation we can see that:
We can see both PLZ8_ANTG3 and PLZ8_ANTG4 increase togther having +ve corelation, since large families (6-10 and 10+) share the same size of house hold.
PLZ8_ANTG3 and CAMEO_INTL_2015_WEALTH we can see a +ve co-relation which seems to indicate large families are poor
In the negative cor-relation we can see that:
MOBI_REGIO,PLZ8_ANTG1 and FINANZ_MINIMALIST that smaller families in the PLZ8 region tend to be less interested in finicial matters and they move less compared to the larger densities.these are related to movement patterns.PCA-2
- ALTERSKATEGORIE_GROB: Estimated age based on given name analysis
- SEMIO_REL: Personality typology, for each dimension
- FINANZ_SPARER: Financial typology
- FINANZ_VORSORGER: Financial typology
- PRAEGENDE_JUGENDJAHRE_DECADE: Generation by the decade
- SEMIO_PFLICHT: Personality typology
In the positive co-relation we can see that:
ALTERSKATEGORIE_GROB, FINANZ_VORSORGER and SEMIO_ERL It seems that this component is related more to personality, age and financial readiness.
In the negative weights:
SEMIO_REL, FINANZ_SPARER, PRAEGENDE_JUGENDJAHRE_DECADE we can that older religous people tend to save money more.
PCA-3
- ANREDE_KZ: Gender
- SEMIO_VERT: Personality typology
- SEMIO_KAEM: Personality typology
- SEMIO_DOM: Personality typology
- SEMIO_KRIT: Personality typology
- SEMIO_FAM: Personality typology
This component is purely psychological.
For the positive corelations:
VERT, SOZ and FAM it indicates dreamful, socially-minded and family minded a person is.
For the negative corelations:
ANREDE_KZ, SEMIO_KAEM, SEMIO_DOM, KRIT, SEMIO_RAT they type of gender and personalities that have combative attitude, dominant-minded, critical and rational .. they seem to be mostly men.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.X_pca_sample = pd.DataFrame(X_pca).sample(frac=0.2, random_state=1)
print("Original rows:",len(X_pca),"\nSample rows:", len(X_pca_sample))
# Over a number of different cluster counts...
start_time = time.time()
def do_kmeans_scores(data, n_cluster, njobs):
def kmeans_fit(data,n_cluster, njobs):
kmeans = KMeans(n_clusters = n_cluster, n_jobs=njobs)
model = kmeans.fit(data)
return np.abs(model.score(data))
scores = []
for k in list(range(1,n_cluster+1)):
st_time = time.time()
score = kmeans_fit(data,k,njobs)
scores.append(score)
end_time = time.time()
print(k,"- Score:",np.round(score),"| Run time: %s mins" % np.round(((end_time - st_time)/60),3))
return scores, print("=== Total Run time: %s mins ===" % np.round(((time.time() - start_time)/60),2))
# run k-means clustering on the data and...
# compute the average within-cluster distances.
scores = do_kmeans_scores(X_pca_sample,30, njobs = -1)
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
plt.plot(list(range(1,30+1)), scores[0], linestyle='--', marker='o', color='b');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans = KMeans(n_clusters = 25, n_jobs=-1)
model = kmeans.fit(X_pca)
azdias_pred = model.predict(X_pca)
There isn't a specific elbow, but we can see the curve and the sum of squared distances error (sse) seems to getting lower. I will choose 25 clusters, since after that the k klusters seems to converge.
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;) delimited.clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers_df = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', sep=';')
customers_df.head(2)
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
customers_clean_df = clean_data(customers_df)
customers_clean_df = customers_clean_df.sub(customers_clean_df.mean())/customers_clean_df.std()
## Fit an imputer ##
mean_imputer.fit(customers_clean_df)
## Transform using imputer ##
mean_imputer.transform(customers_clean_df)
## Validate all nulls are dropped ##
print("[validation] Unique nulls sum: ",np.unique(customers_clean_df.isnull().sum(axis=1)))
customers_pca, customers_X_pca = do_pca(25,customers_clean_df)
customers_pred = model.predict(customers_X_pca)
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot() or barplot() function could be handy..inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.
figure, axs = plt.subplots(nrows=1, ncols=2, figsize = (15,5))
figure.subplots_adjust(hspace = 1, wspace=.3)
sns.countplot(customers_pred, ax=axs[0])
axs[0].set_title('Customer Clusters')
sns.countplot(azdias_pred, ax=axs[1])
axs[1].set_title('General Clusters')
#general_pred_df = pd.DataFrame(azdias_pred, columns=['count'])['count'].value_counts().sort_index()
general_pred_df = pd.DataFrame(pd.DataFrame(azdias_pred, columns=['count'])['count'].value_counts().sort_index())
general_pred_df['prop'] = general_pred_df['count'] / len(azdias_pred)
customers_pred_df = pd.DataFrame(pd.DataFrame(customers_pred, columns=['count'])['count'].value_counts().sort_index())
customers_pred_df['prop'] = customers_pred_df['count'] / len(customers_pred)
fig = go.Figure()
fig.update_layout(
title = {'text':'General vs. Customers proportions', 'x': 0.5},
xaxis_title = "clusters",
yaxis_title = "proportions",
xaxis = dict(
tickmode = 'linear',
tick0 = 0,
dtick = 1
)
)
fig.add_trace(go.Bar(x=general_pred_df.index,
y=general_pred_df['prop'],
name='General',
marker_color='#ABDDDE'
))
fig.add_trace(go.Bar(x=customers_pred_df.index,
y=customers_pred_df['prop'],
name='Customers',
marker_color='rgb(244, 181, 189)'
))
# Check difference in cluster proportion for general vs customer populations
prop_diff = (customers_pred_df.prop-general_pred_df.prop).sort_values(ascending=False)
print("over-represented:")
display(prop_diff[0:3])
print("under-represented:")
display(prop_diff[-3:])
prop_diff.sort_index(inplace=True)
fig = go.Figure()
fig = go.Figure(data=go.Scatter(x=prop_diff.index,
y=prop_diff.values,
mode='lines+markers',
line_color='#ABDDDE',
marker_color='rgb(244, 181, 189)'))
fig.update_layout(title = {'text':'General vs. Customers proportions', 'x': 0.5},
xaxis = dict(
title = "clusters",
tickmode = 'linear',
tick0 = 0,
dtick = 1),
yaxis_title = "proportions"
)
fig.show()
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
pca_inv_df_cent12 = pd.DataFrame(customers_pca.inverse_transform(customers_X_pca[customers_pred == 12]))
target_cent_12 = pca_inv_df_cent12.mul(pca_inv_df_cent12.std())+pca_inv_df_cent12.mean()
target_cent_12.columns = customers_clean_df.columns
target_cent_12.describe()
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
pca_inv_df_cent21 = pd.DataFrame(pca.inverse_transform(X_pca[azdias_pred == 21]))
outside_cent_21 = pca_inv_df_cent21.mul(pca_inv_df_cent21.std())+pca_inv_df_cent21.mean()
outside_cent_21.columns = azdias_clean_df.columns
outside_cent_21.describe()
columns_idx_inter = pd.Index.intersection(pca_inv_df_cent12.columns,pca_inv_df_cent21.columns)
print("Common columns:", len(columns_idx_inter))
columns_idx_inter
income_cols = ['FINANZ_MINIMALIST', 'KBA05_ANTG1','PLZ8_ANTG4','HH_EINKOMMEN_SCORE','GREEN_AVANTGARDE']
def col_check(col, col_idx):
matched_cols = []
if all(x in list(col_idx) for x in col):
print("All columns exist")
else:
print("One or more column(s) doesn't exist, Matched ones are")
for x in col:
if x in list(col_idx):
print(x)
col_check(income_cols,columns_idx_inter)
target_cent_12[income_cols].mean()
outside_cent_21[income_cols].mean()
I've chosen finanicial columns to assess the two clusters. It seems that cluster 12 seems to be more finanicial while cluster 21 is not. The finanicial cluster is targeted by the mailing company.